package com.snail.snailvr.player;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.snail.media.player.ISnailPlayer;
import com.snail.snailvr.R;
import com.snail.snailvr.model.History;
import com.snail.snailvr.utils.Constant;
import com.snail.snailvr.utils.DatabaseUtils;
import com.snail.snailvr.utils.DialogUtils;
import com.snail.snailvr.utils.LogUtils;
import com.snail.snailvr.utils.SharedPreferencesUtil;
import com.snail.snailvr.utils.ToastUtils;
import com.snail.snailvr.utils.Util;
import com.snail.snailvr.views.BaseToolbarActivity;
import com.snail.snailvr.views.adapter.HistoryAdapter;
import com.snail.snailvr.widget.HorizontalDividerItemDecoration;
import com.snail.snailvr.widget.WrapContentLinearLayoutManager;
import com.snail.snailvr.widget.seekbar.DiscreteSeekBar;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import rx.Subscriber;
import rx.Subscription;

import static com.snail.snailvr.R.id.history;
import static com.snail.snailvr.R.id.toolbar;

public class PlayActivity extends BaseToolbarActivity implements View.OnClickListener {
    private static final int TYPE_360_3D_Left_Right=0;
    private static final int TYPE_360_3D_Up_Down=1;
    public static final int TYPE_360_2D=2;
    private static final int TYPE_180_3D_Left_Right=3;
    private static final int TYPE_180_3D_Up_Down=4;
    private static final int TYPE_180_2D=5;
    private static final int TYPE_2D=6;

    private int mPlayMode = TYPE_360_2D;

    private static final long ANIMATION_DURATION = 300;
    private static final int HIDE_UI_DELAY_TIME = 1000 * 8;
    private static final int HIDE_UI_WHAT = 10;
    public  static final int FOV_DEFAULT = 90;
    private static final String KEY_IS_ON_GLASS = "key_is_on_glass";
    @Bind(toolbar)
    Toolbar mToolbar;
    @Bind(R.id.framecontainer)
    View mFramecontainer;
    //history
    @Bind(R.id.list)
    RecyclerView mRecyclerView;
    @Bind(R.id.empty_view)
    View mEmptyView;
    @Bind(R.id.history_layout)
    View mHistoryLayout;
    private Subscription mGetHistoryVideosSubscription;
    private List<History> mHistoryList;
    private HistoryAdapter mAdapter;
    private String videoName;
    private HideUiHandler mHideUiHandler;

    private static final String TAG = "PlayActivity";

    private SnailPlayerVideoView mVideoView;

    private ImageView mImageView_PlayPause;

    private RelativeLayout mBufferingView;
    private TextView mTextViewBufferPercent;

    private String mPlayUrl = "";

    private GestureDetector mGestureDetector = null;

    private static final int GESTURE_TYPE_NO = 0;
    private static final int GESTURE_TYPE_HRO = 1;
    private static final int GESTURE_TYPE_VER = 2;

    public static final int SNVR_PROJ_PLANE = 0;
    public static final int SNVR_PROJ_SPHERE = 1;
    public static final int SNVR_PROJ_DOME = 2;

    public static final int SNVR_VIDEO_SPLICE_FMT_2D = 0;
    public static final int SNVR_VIDEO_SPLICE_FMT_3D_SBS = 1;
    public static final int SNVR_VIDEO_SPLICE_FMT_3D_OVU = 2;

    public static final int SNVR_NAVIGATION_SENSOR = 0;
    public static final int SNVR_NAVIGATION_TOUCH = 1;
    public static final int SNVR_NAVIGATION_BOTH = 2;

    public static final int SNVR_SINGLE_EYES_MODE = 0;
    public static final int SNVR_DOUBLE_EYES_MODE = 1;

    private int cur_gesture_type = GESTURE_TYPE_NO;
    private int cur_aspect_type = SnailPlayerVideoView.ASPECT_TYEP_AUTO_FIT;

    private boolean mIsPrepared = false;

    private boolean mIsVRMode = true;

    private boolean mShowing = true;

    private AudioManager mAudioManager;

    private static final int SHOW_PROGRESS = 2;
    private int pausePostion;
    /**
     * 最大声音
     */
    private int mMaxVolume;
    /**
     * 当前声音
     */
    private int mVolume = -1;
    /**
     * 当前亮度
     */
    private float mBrightness = -1f;
    /**
     * 调节亮度和声音的控件
     */
    private RelativeLayout mOperLayout;
    private ImageView mOperationBg;
    private TextView mOperTextView;

    private FrameLayout mLayoutPlayerControllerFull;

    private SeekBar mSeekBar;
    private TextView mCurrentTime;
    private TextView mEndTime;
    private int mDuration;
    private boolean mDragging;

    private boolean mIsLive = true;

    private int mFov = this.FOV_DEFAULT;
    private int mNavigationMode = PlayActivity.SNVR_NAVIGATION_SENSOR;
    private int mEyesMode = PlayActivity.SNVR_DOUBLE_EYES_MODE;

    private boolean isOFFGlass=false;


    private String regEx_180_2D = "^.*_180(\\.\\w*)?$";
    private String regEx_180_TB = "^.*_180_TB(\\.\\w*)?$";
    private String regEx_180_LR = "^.*_180_LR(\\.\\w*)?$";
    private String regEx_360_2D = "^.*_360(\\.\\w*)?$";
    private String regEx_360_TB = "^.*_360_TB(\\.\\w*)?$";
    private String regEx_360_LR = "^.*_360_LR(\\.\\w*)?$";

    // 网络处理
    private SnailNetReceiver mNetReceiver;
    private SnailNetReceiver.NetStateChangedListener mNetChangedListener;

    private String mNetType = "";
    private StringBuilder mNetChange = new StringBuilder();
    private String mErroCode = "";
    private long mStartCacheTime;
    private long maxCacheTime;

    private boolean mIsFirstRegistNet = true;

    @Override
    protected void handleIntent() {
        mPlayUrl = getIntent().getStringExtra(Definition.KEY_PLAY_URL);
        videoName = getIntent().getStringExtra(Constant.KEY_VIDEO_NAME);
        isOFFGlass = getIntent().getBooleanExtra(Constant.KEY_IS_NORMAL, false);
        updateHistoryList(mPlayUrl, videoName);
        LogUtils.d("playurl="+mPlayUrl);
        if (mPlayUrl == null) {
            getPlayUrlFromIntent(getIntent());
        }
    }

    /**
     * 外部打开播放器(比如从文件管理器打开视频选择OXPlayer播放)
     * @param intent
     */
    private void getPlayUrlFromIntent(Intent intent) {
        String action = intent.getAction();
        String type = intent.getType();
        if (!TextUtils.isEmpty(action)) {
            if (action.equals(Intent.ACTION_VIEW) && !TextUtils.isEmpty(type)) {
                if (type.startsWith("video/")) {
                    Uri uri = intent.getData();
                    if (uri != null) {
                        mPlayUrl = uri.getPath();
                        if (mPlayUrl != null && !mPlayUrl.endsWith("/") && mPlayUrl.contains("/"))
                            videoName = mPlayUrl.substring(mPlayUrl.lastIndexOf("/") + 1, mPlayUrl.length());
                        LogUtils.d("videoName=" + videoName);

                    }
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        initNetState();
    }

    private void initNetState() {
        mNetReceiver = SnailNetReceiver.getInstance();
        mNetChangedListener = new SnailNetReceiver.NetStateChangedListener() {

            @Override
            public void onNetStateChanged(SnailNetReceiver.NetState netCode) {
                mNetType = netCode.name();
                if (!mIsFirstRegistNet) {
                    mNetChange.append("-->" + netCode.name());
                }
                mIsFirstRegistNet = false;
            }
        };

    }


    void initPlayModeFromName(String _name) {
        Pattern p = null;
        Matcher m = null;

        p = Pattern.compile(regEx_180_2D);
        m = p.matcher(_name);

        if (m.matches()) {
            mPlayMode = TYPE_180_2D;
            return;
        }

        p = Pattern.compile(regEx_180_LR);
        m = p.matcher(_name);

        if (m.matches()) {
            mPlayMode = TYPE_180_3D_Left_Right;
            return;
        }

        p = Pattern.compile(regEx_180_TB);
        m = p.matcher(_name);

        if (m.matches()) {
            mPlayMode = TYPE_180_3D_Up_Down;
            return;
        }

        p = Pattern.compile(regEx_360_2D);
        m = p.matcher(_name);

        if (m.matches()) {
            mPlayMode = TYPE_360_2D;
            return;
        }

        p = Pattern.compile(regEx_360_LR);
        m = p.matcher(_name);

        if (m.matches()) {
            mPlayMode = TYPE_360_3D_Left_Right;
            return;
        }

        p = Pattern.compile(regEx_360_TB);
        m = p.matcher(_name);

        if (m.matches()) {
            mPlayMode = TYPE_360_3D_Up_Down;
            return;
        }

        mPlayMode = TYPE_360_2D;//SharedPreferencesUtil.getInstance(this).getPlayModel();

    }

    @Override
    protected void initView() {
        initSp();
        setupToolbar(mToolbar, R.color.volume_layout_bg, R.color.toolbar_title_color, videoName, R.menu.menu_player);
        fitSystemWindows();
        mVideoView = (SnailPlayerVideoView) findViewById(R.id.id_videoview);
        mVideoView.setVideoPlayerType(ISnailPlayer.PlayerType.PLAYER_TYPE_SNAIL_VR);
        mVideoView.setPlayFov(mFov);


        initPlayModeFromName(videoName);

        setPlayModel(mPlayMode);
        mVideoView.setNavigationmode(mNavigationMode);

        initMenuIcon();

        mLayoutPlayerControllerFull = (FrameLayout) findViewById(R.id.media_controller);


        mSeekBar = (SeekBar) findViewById(R.id.id_video_player_seekbar);
        mCurrentTime = (TextView) findViewById(R.id.id_video_player_current_time);
        mEndTime = (TextView) findViewById(R.id.id_video_player_total_time);
        mSeekBar.setThumbOffset(1);
        mSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
				 mVideoView.seekTo(seekBar.getProgress());
                mHandler.removeMessages(SHOW_PROGRESS);
                mDragging = false;
                mHandler.sendEmptyMessageDelayed(SHOW_PROGRESS, 1000);
                mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC, false);
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                                          boolean fromUser) {
                if (!fromUser)
                    return;
				String time = generateTime(progress);
				if (mCurrentTime != null)
					mCurrentTime.setText(time);
				
			}

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                mHandler.removeMessages(SHOW_PROGRESS);
                mDragging = true;
                mAudioManager.setStreamMute(AudioManager.STREAM_MUSIC, true);
            }

        });


        mVideoView.setOnStatListener(new ISnailPlayer.ISnailPlayerStateChangeNotification() {
            @Override
            public void notify(ISnailPlayer mp, ISnailPlayer.State state) {
                if (state == ISnailPlayer.State.PLAYER_STARTED) {
                    initSavedOption();
                    mVideoView.start();
                    mImageView_PlayPause
                            .setImageResource(R.drawable.ic_player_pause);
                    mBufferingView.setVisibility(View.GONE);
                    mIsPrepared = true;
                    mDuration = mVideoView.getDuration();
                    if (mDuration == 0) {
                        mIsLive = true;
                        mSeekBar.setEnabled(false);
                    } else {
                        mIsLive = false;
                        mSeekBar.setEnabled(true);
                        mHandler.sendEmptyMessageDelayed(SHOW_PROGRESS, 1000);
                    }

                    Log.d(TAG, "player duration :" + mDuration);
                }
            }
        });


        mVideoView.setOnEventListener(new ISnailPlayer.ISnailPlayerEventNotification() {
            @Override
            public boolean notify(ISnailPlayer player, ISnailPlayer.EventType type, int i) {

                if(type == ISnailPlayer.EventType.PLAYER_EVENT_BUFFERING){

                    Log.i(TAG, "PLAYER_EVENT_BUFFERING");
                    mBufferingView.setVisibility(View.VISIBLE);
                }else if(type == ISnailPlayer.EventType.PLAYER_EVENT_BUFFERED){

                    Log.i(TAG, "PLAYER_EVENT_BUFFERED");
                    mBufferingView.setVisibility(View.GONE);
                }else if(type == ISnailPlayer.EventType.PLAYER_EVENT_FINISHED){

                    Log.d(TAG, "PLAYER_EVENT_FINISHED ");
                    mIsPrepared = false;
                    mBufferingView.setVisibility(View.GONE);
                }

                return true;
            }
        });

        mVideoView.setOnErrorListener(new ISnailPlayer.ISnailPlayerErrorNotification() {
            @Override
            public void onError(ISnailPlayer mp, ISnailPlayer.ErrorType error, int extra) {
                LogUtils.d("error==="+error+":"+extra);
                mErroCode = "error code:(" + error + "," + extra + ")";
                ToastUtils.showPlayerErrorToast(getString(R.string.play_error));
                mBufferingView.setVisibility(View.GONE);
                mIsPrepared = false;
            }
        });


        mImageView_PlayPause = (ImageView) findViewById(R.id.id_imageview_play_pause_full);
        mImageView_PlayPause.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if(!mIsPrepared)
                    return;
                reSendHideMessage();
                if (mVideoView.isPlaying()) {
                    mImageView_PlayPause.setImageResource(R.drawable.ic_player_play);
                    mVideoView.pause();
                } else {
                    mImageView_PlayPause.setImageResource(R.drawable.ic_player_pause);
                    if(mVideoView.getDuration() > 0)
                       mVideoView.start();
                    else {
                        mVideoView.stopPlayback();
                        mVideoView.setVideoPath(mPlayUrl);
                        mBufferingView.setVisibility(View.VISIBLE);
                    }

                }
            }
        });

        mBufferingView = (RelativeLayout) findViewById(R.id.id_mediaplay_buffering_view);
        mTextViewBufferPercent = (TextView) findViewById(R.id.tv_buffering);

        // 声音和亮度调节图标
        mOperLayout = (RelativeLayout) findViewById(R.id.layout_volume_bright_transparent);
        mOperLayout.setVisibility(View.GONE);
        mOperationBg = (ImageView) findViewById(R.id.video_player_voiceortranparent_img);
        mOperTextView = (TextView) findViewById(R.id.video_player_voiceortranparent_value);

        mGestureDetector = new GestureDetector(this, new OnGestureListener() {

            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                toggleMediaControlsVisiblity();
                return true;
            }

            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2,
                                    float distanceX, float distanceY) {
                Log.i(TAG, "onScroll");
                if (e1 == null || e2 == null)
                    return true;

                float nFristX = e1.getX();
                float nFristY = e1.getY();

                // Log.i(TAG, " nFristX:" + nFristX + " nFristY:" + nFristY);

                int video_width = mVideoView.getWidth();
                int video_height = mVideoView.getHeight();
                Log.i(TAG, " video_width:" + video_width);

                float nCurrentX = e2.getRawX();
                float nCurrentY = e2.getRawY();

                int movePosX = (int) Math.abs(distanceX);
                int movePosY = (int) Math.abs(distanceY);

                // Log.i(TAG, "movePosX:" + movePosX + " movePosY:" + movePosY);

                if (mNavigationMode != SNVR_NAVIGATION_SENSOR) {
                    float phi = distanceX * 360 / video_width;
                    float theta = distanceY * mFov / video_height;
                    mVideoView.setTouchInfo(phi, theta);

                } else {
                    getGestureDirection(movePosX, movePosY);

                    if (cur_gesture_type == GESTURE_TYPE_VER) {
                        float _percent = (nFristY - nCurrentY) / video_height;

                        if (nFristX > video_width / 2) {
                            Log.i(TAG, "right");
                            onVolumeSlide(_percent);
                        } else {
                            Log.i(TAG, "Left");
//							onBrightnessSlide(_percent);
                        }
                    } else if (cur_gesture_type == GESTURE_TYPE_HRO) {
                        Log.i(TAG, "横向移动");
                    }

                }

                return true;
            }

            @Override
            public boolean onDown(MotionEvent e) {
                // TODO Auto-generated method stub
                return true;
            }

            @Override
            public void onShowPress(MotionEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onLongPress(MotionEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2,
                                   float velocityX, float velocityY) {
                return false;
            }
        });

        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        mMaxVolume = mAudioManager
                .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        mVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

        mVideoView.setVideoPath(mPlayUrl);
        ImageView mHistoryView = (ImageView) findViewById(history);
        mHistoryView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                hideUI();
                showHistoryLayout();

            }
        });
        mHideUiHandler = new HideUiHandler();
        setupHistory();
    }

    private void savePlayModel(int playModel) {
        SharedPreferencesUtil.getInstance(this).setPlayModel(playModel);
//        uiutils.setPreferenceKeyIntValue(
//                getApplicationContext(),
//                Definition.KEY_PROJECTIONTYPE, mProjectionType);
    }

    /**
     * 初始化保存选项
     */
    private void initSavedOption() {
//        mVideoView.setProjectionType(mProjectionType);
        initEysMode();
    }

    private void initSp() {
        mFov = uiutils.getPreferenceKeyIntValue(getApplicationContext(),
                Definition.KEY_FOV, FOV_DEFAULT);
//        mProjectionType = uiutils.getPreferenceKeyIntValue(
//                getApplicationContext(), Definition.KEY_PROJECTIONTYPE,
//                PlayActivity.SNVR_PROJ_PLANE);
//        mVideoSpliceFormat = uiutils.getPreferenceKeyIntValue(
//                getApplicationContext(), Definition.KEY_VIDEOSPLICEFORMAT,
//                PlayActivity.SNVR_VIDEO_SPLICE_FMT_2D);
//        mNavigationMode = uiutils.getPreferenceKeyIntValue(this, Definition.KEY_SENSORMODE, SNVR_NAVIGATION_SENSOR);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_player;
    }

    @Override
    protected void onStart() {
        super.onStart();
        LogUtils.i("TEST","onStart()");
    }

    @Override
    protected void onResume() {
        super.onResume();
        mIsFirstRegistNet = true;
        mNetReceiver.registNetBroadCast(this);
        mNetReceiver.addNetStateChangeListener(mNetChangedListener);
        LogUtils.i("TEST","onResume()");
    }

    @Override
    protected void onPause() {
        pausePostion = mVideoView.getCurrentPosition();
        mVideoView.pause();
        mNetReceiver.remoteNetStateChangeListener(mNetChangedListener);
        mNetReceiver.unRegistNetBroadCast(this);
		super.onPause();
        LogUtils.i("TEST","onPause()");
    }

    @Override
    protected void onStop() {
        super.onStop();
        LogUtils.i("TEST","onStop()");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtils.i("TEST","onDestroy()");
        mHandler.removeMessages(SHOW_PROGRESS);
        if (mVideoView != null) {
            mVideoView.stopPlayback();
            mVideoView = null;
        }
        if (mHideUiHandler != null)
            mHideUiHandler.removeCallbacksAndMessages(null);

        if (mGetHistoryVideosSubscription != null && !mGetHistoryVideosSubscription.isUnsubscribed())
            mGetHistoryVideosSubscription.unsubscribe();

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mGestureDetector.onTouchEvent(event))
            return true;
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_UP:
                endGesture();
                return true;
        }
        return super.onTouchEvent(event);
    }

    private void endGesture() {
        // TODO Auto-generated method stub
        mVolume = -1;
        mBrightness = -1f;
        cur_gesture_type = GESTURE_TYPE_NO;
        mOperLayout.setVisibility(View.GONE);
    }

    private void getGestureDirection(float nX, float nY) {

        if (cur_gesture_type == GESTURE_TYPE_NO) {
            if (nX == 0) {
                if (nY > 15) {
                    cur_gesture_type = GESTURE_TYPE_VER;
                }
            } else if (nY == 0) {
                if (nX > 5) {
                    cur_gesture_type = GESTURE_TYPE_HRO;
                }
            } else {
                if (nX / nY > 3) {
                    cur_gesture_type = GESTURE_TYPE_HRO;
                } else if (nY / nX > 3) {
                    cur_gesture_type = GESTURE_TYPE_VER;
                }
            }
        }
    }

    /**
     * 滑动改变声音大小
     *
     * @param percent
     */
    private void onVolumeSlide(float percent) {
        if (mVolume == -1) {
            mVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            if (mVolume < 0)
                mVolume = 0;
            // 显示
            mOperationBg.setImageResource(R.drawable.video_player_voice);
            mOperLayout.setVisibility(View.VISIBLE);
        }

        int index = (int) (percent * mMaxVolume) + mVolume;
        if (index > mMaxVolume)
            index = mMaxVolume;
        else if (index < 0)
            index = 0;

        // 变更声音
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, index, 0);

        // 变更进度条
        int present = index * 100 / mMaxVolume;
        Log.i(TAG, "present is:" + present);
        mOperTextView.setText(String.valueOf(present) + "%");
    }

    /**
     * 滑动改变亮度
     *
     * @param percent
     */
    private void onBrightnessSlide(float percent) {
        if (mBrightness < 0) {
            mBrightness = getWindow().getAttributes().screenBrightness;
            if (mBrightness <= 0.00f)
                mBrightness = 0.50f;
            if (mBrightness < 0.01f)
                mBrightness = 0.01f;

            // 显示
            mOperationBg.setImageResource(R.drawable.video_player_bright);
            mOperLayout.setVisibility(View.VISIBLE);
        }
        WindowManager.LayoutParams lpa = getWindow().getAttributes();
        lpa.screenBrightness = mBrightness + percent;
        if (lpa.screenBrightness > 1.0f)
            lpa.screenBrightness = 1.0f;
        else if (lpa.screenBrightness < 0.01f)
            lpa.screenBrightness = 0.01f;
        getWindow().setAttributes(lpa);

        int present = (int) (lpa.screenBrightness * 100);
        Log.i(TAG, "present is:" + present);
        mOperTextView.setText(String.valueOf(present) + "%");

    }

    private void toggleMediaControlsVisiblity() {

        if (mHideUiHandler != null)
            mHideUiHandler.removeMessages(HIDE_UI_WHAT);
        if (mLayoutPlayerControllerFull.getTranslationY() == mLayoutPlayerControllerFull.getHeight()) {
            mShowing = true;
            updatePausePlay();
            mHandler.sendEmptyMessage(SHOW_PROGRESS);
            //snailVR
            showUI();
        } else {
            mShowing = false;
            mHandler.removeMessages(SHOW_PROGRESS);
            //snailVR
            hideUI();
        }

    }

    private static String generateTime(long position) {
        int totalSeconds = (int) (position / 1000);

        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;

        if (hours > 0) {
            return String.format(Locale.US, "%02d:%02d:%02d", hours, minutes,
                    seconds).toString();
        } else {
            return String.format(Locale.US, "%02d:%02d", minutes, seconds)
                    .toString();
        }
    }

    private void updatePausePlay() {
        if (mVideoView.isPlaying()) {
            mImageView_PlayPause.setImageResource(R.drawable.ic_player_pause);
        } else {
            mImageView_PlayPause.setImageResource(R.drawable.ic_player_play);
        }
    }


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            long pos;
            if (msg.what == SHOW_PROGRESS) {
                pos = setProgress();
				mSeekBar.setMax(mVideoView.getDuration());
                if (!mDragging && mShowing) {
                    msg = obtainMessage(SHOW_PROGRESS);
                    sendMessageDelayed(msg, 1000 - (pos % 1000));
                    updatePausePlay();
                }

            }
        }
    };

    private long setProgress() {
        if (mVideoView == null || mDragging)
            return 0;

        int position = mVideoView.getCurrentPosition();
        int duration = mVideoView.getDuration();
        if (mSeekBar != null) {
            if (duration > 0) {
				//long pos = 1000L * position / duration;
				mSeekBar.setProgress(position);
			}
			int percent = mVideoView.getBufferPercentage();
			mSeekBar.setSecondaryProgress(percent);
		}

        mDuration = duration;

        if (mEndTime != null && !mIsLive)
            mEndTime.setText(generateTime(mDuration));
        if (mCurrentTime != null)
            mCurrentTime.setText(generateTime(position));

        return position;
    }

    /**
     * 点击顶部或者底部menu时需要resend
     */
    private void reSendHideMessage() {
        if (mHideUiHandler != null) {
            mHideUiHandler.removeMessages(HIDE_UI_WHAT);
            mHideUiHandler.sendEmptyMessageDelayed(HIDE_UI_WHAT, HIDE_UI_DELAY_TIME);
        }
    }

    /**
     * 更具配置文件更新menu图标
     */
    private void initMenuIcon() {
        Menu menu = mToolbar.getMenu();
        menu.findItem(R.id.projection_type).setIcon(getResources().getDrawable(Util.getPlayModelResId(mPlayMode)));
//        menu.findItem(R.id.splice_format).setIcon(getResources().getDrawable(Util.getSpliceFormatResId(mVideoSpliceFormat)));
        menu.findItem(R.id.menu_navigation_mode).setIcon(getResources().getDrawable(Util.getNavigationModeResId(mNavigationMode)));
    }

    private void setupHistory() {
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(this));
        mHistoryList = new ArrayList<>();
        mAdapter = new HistoryAdapter(this, mHistoryList, this, true);
        mRecyclerView.setAdapter(mAdapter);
        addDivider();
        loadHistory();
    }

    protected void addDivider() {
        HorizontalDividerItemDecoration horizontalDividerItemDecoration = new HorizontalDividerItemDecoration.Builder(this)
                .paintProvider(mAdapter)
                .visibilityProvider(mAdapter)
                .marginProvider(mAdapter)
                .build();
        horizontalDividerItemDecoration.setBackgroundPaintColor(getResources().getColor(R.color.list_item_color_normal));
        mRecyclerView.addItemDecoration(horizontalDividerItemDecoration);
    }

    private void loadHistory() {
        mGetHistoryVideosSubscription = DatabaseUtils.getPlayHistory(new Subscriber<History>() {
            @Override
            public void onCompleted() {
                mAdapter.notifyItemRangeInserted(0, mHistoryList.size());
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(History history) {
                mHistoryList.add(history);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.history_item_layout:
                hideHistoryLayout();
                History history = (History) v.getTag();
                if (history != null && !history.getPath().equals(mPlayUrl)) {
                    mPlayUrl = history.getPath();
                    mVideoView.stopPlayback();
                    mVideoView.setVideoPath(mPlayUrl);
                    initPlayModeFromName(history.getName());
                    setPlayModel(mPlayMode);
                    mBufferingView.setVisibility(View.VISIBLE);
                    //mVideoView.start();
                    updateToolbarTitle(history.getName());

                }
                break;
        }
    }

    private void updateToolbarTitle(String name) {
        TextView titleView=(TextView) mToolbar.findViewById(R.id.toolbar_title);
        if(titleView!=null)
            titleView.setText(name);
    }

    class HideUiHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == HIDE_UI_WHAT) {
                hideUI();
            }
        }
    }

    private void showUI() {
        mLayoutPlayerControllerFull.animate().translationY(0).setDuration(0).setInterpolator(new AccelerateInterpolator()).start();
        mToolbar.animate().translationY(0).setDuration(0).setInterpolator(new AccelerateInterpolator()).start();
        hideHistoryLayout();
        mHideUiHandler.sendEmptyMessageDelayed(HIDE_UI_WHAT, HIDE_UI_DELAY_TIME);

        fitSystemWindows();

    }

    private void fitSystemWindows() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mFramecontainer.setFitsSystemWindows(false);
            mFramecontainer.setPadding(0, 0, 0, 0);
        }
    }

    private void hideUI() {
        mLayoutPlayerControllerFull.animate().translationY(mLayoutPlayerControllerFull.getHeight()).setDuration(ANIMATION_DURATION).setInterpolator(new DecelerateInterpolator()).start();
        mToolbar.animate().translationY(-mToolbar.getHeight()).setDuration(ANIMATION_DURATION).setInterpolator(new DecelerateInterpolator()).start();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mFramecontainer.setFitsSystemWindows(true);
        }
    }

    private void hideHistoryLayout() {
        mHistoryLayout.animate().translationX(mHistoryLayout.getWidth()).setDuration(ANIMATION_DURATION).setInterpolator(new DecelerateInterpolator()).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mHistoryLayout.setVisibility(View.GONE);
            }
        }).start();
    }

    private void showHistoryLayout() {
        mHistoryLayout.animate().translationX(0).setDuration(ANIMATION_DURATION).setInterpolator(new DecelerateInterpolator()).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mHistoryLayout.setVisibility(View.VISIBLE);
            }
        }).start();
    }

    @Override
    protected boolean onToolbarMenuItemClick(MenuItem item) {
        int id = item.getItemId();

        switch (id) {
            case R.id.glass_state:
                changeGlassState(item);
                break;
            case R.id.projection_type:
                popProjectionTypeDialog(item);
                break;
//            case R.id.splice_format:
//                if(!isOFFGlass)
//                    popSpliceFormatDialog(item);
//                break;
            case R.id.menu_reset_angle:
                if (mVideoView != null) {
                    mVideoView.setOriginalAngle();
                    ToastUtils.showPlayerToast(getString(R.string.reset_origin_angle));
                }
                break;
            case R.id.menu_navigation_mode:
                setNavigationMode(item);
                break;
            case R.id.menu_angle_setting:
                popAngleDialog();
                break;
            default:
                return super.onOptionsItemSelected(item);
        }
        reSendHideMessage();
        return true;
    }

    /**
     * 是否是戴眼镜的状态
     *
     * @param item
     */
    public void changeGlassState(final MenuItem item) {
        int which;
        if (isOFFGlass) {
            item.setIcon(R.drawable.ic_player_glasses);
            which = 1;
            SharedPreferencesUtil.getInstance(this).setGlassState(Constant.GLASS_ON);
        } else {
            item.setIcon(R.drawable.ic_player_no_glasse);
            which = 0;
            SharedPreferencesUtil.getInstance(this).setGlassState(Constant.GLASS_OFF);
        }
        isOFFGlass=!isOFFGlass;
        mEyesMode = which;
        mVideoView.setEyesMode(mEyesMode);
    }

    private void popProjectionTypeDialog(final MenuItem item) {
        DialogUtils.showSingleChoiceDialog(this, getString(R.string.select_projectin_dialog_title), getResources().getStringArray(R.array.projection_arrays),
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int position = (int) v.getTag();

                        setPlayModel(position);
                        mPlayMode = position;

                        if (PlayActivity.SNVR_PROJ_PLANE == position) {
                            item.setIcon(R.drawable.ic_player_plane);
                        } else if (PlayActivity.SNVR_PROJ_SPHERE == position) {
                            item.setIcon(R.drawable.ic_player_sphere);
                        } else if (PlayActivity.SNVR_PROJ_DOME == position) {
                            item.setIcon(R.drawable.ic_player_dome);
                        }

//                        mProjectionType = position;
//                        Log.d(TAG, "selected projection = " + mProjectionType);
//                        mVideoView.setProjectionType(mProjectionType);
                        savePlayModel(position);
                    }
                }
                , mPlayMode);
    }

    /**
     * 设置播放模式
     * @param position
     */
    private void setPlayModel(int position) {
        switch (position){
            case TYPE_360_3D_Left_Right:
                mVideoView.setProjectionType(SNVR_PROJ_SPHERE);
                mVideoView.setVideoSpliceFormat(SNVR_VIDEO_SPLICE_FMT_3D_SBS);
                break;
            case TYPE_360_3D_Up_Down:
                mVideoView.setProjectionType(SNVR_PROJ_SPHERE);
                mVideoView.setVideoSpliceFormat(SNVR_VIDEO_SPLICE_FMT_3D_OVU);
                break;
            case TYPE_360_2D:
                mVideoView.setProjectionType(SNVR_PROJ_SPHERE);
                mVideoView.setVideoSpliceFormat(SNVR_VIDEO_SPLICE_FMT_2D);
                break;
            case TYPE_180_3D_Left_Right:
                mVideoView.setProjectionType(SNVR_PROJ_DOME);
                mVideoView.setVideoSpliceFormat(SNVR_VIDEO_SPLICE_FMT_3D_SBS);
                break;
            case TYPE_180_3D_Up_Down:
                mVideoView.setProjectionType(SNVR_PROJ_DOME);
                mVideoView.setVideoSpliceFormat(SNVR_VIDEO_SPLICE_FMT_3D_OVU);
                break;
            case TYPE_180_2D:
                mVideoView.setProjectionType(SNVR_PROJ_DOME);
                mVideoView.setVideoSpliceFormat(SNVR_VIDEO_SPLICE_FMT_2D);
                break;
            case TYPE_2D:
                mVideoView.setProjectionType(SNVR_PROJ_PLANE);
                break;
        }
    }

    private void popSpliceFormatDialog(final MenuItem item) {
//        DialogUtils.showSingleChoiceDialog(this, getString(R.string.select_format_dialog_title), getResources().getStringArray(R.array.display_arrays),
//                null, new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        mVideoView.setVideoSpliceFormat(((int) v.getTag()));
//                    }
//                }
//                , uiutils.getPreferenceKeyIntValue(this, Definition.KEY_VIDEOSPLICEFORMAT,
//                        SNVR_VIDEO_SPLICE_FMT_2D), getString(R.string.cancel), getString(R.string.ok), new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        int which = (int) v.getTag();
//
//
//                        if (PlayActivity.SNVR_VIDEO_SPLICE_FMT_2D == which) {
//                            item.setIcon(R.drawable.ic_player_2d);
//                        } else if (PlayActivity.SNVR_VIDEO_SPLICE_FMT_3D_SBS == which) {
//                            item.setIcon(R.drawable.ic_player_3d_side);
//                        } else if (PlayActivity.SNVR_VIDEO_SPLICE_FMT_3D_OVU == which) {
//                            item.setIcon(R.drawable.ic_player_3d_under);
//                        }
//                        mVideoSpliceFormat = which;
//                        mVideoView.setVideoSpliceFormat(mVideoSpliceFormat);
//                        uiutils.setPreferenceKeyIntValue(
//                                getApplicationContext(),
//                                Definition.KEY_VIDEOSPLICEFORMAT,
//                                mVideoSpliceFormat);
//                    }
//                }
//                , new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        mVideoView.setVideoSpliceFormat(mVideoSpliceFormat);
//                    }
//                });

    }

    private void popAngleDialog() {
        DialogUtils.showSelectFovDialog(this, new DiscreteSeekBar.OnProgressChangeListener() {
                    @Override
                    public void onProgressChanged(DiscreteSeekBar seekBar, int value, boolean fromUser) {

                    }

                    @Override
                    public void onStartTrackingTouch(DiscreteSeekBar seekBar) {
                        reSendHideMessage();
                    }

                    @Override
                    public void onStopTrackingTouch(DiscreteSeekBar seekBar) {
                        mVideoView.setPlayFov(seekBar.getValue());
                    }
                }, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int angle = (int) v.getTag();
                        mFov = angle;
                        mVideoView.setPlayFov(mFov);
                    }
                }
                , new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mVideoView.setPlayFov(mFov);
                    }
                });

    }

    /**
     * 手动模式还是自动模式
     */
    private void setNavigationMode(MenuItem item) {

        switch (mNavigationMode) {
            case SNVR_NAVIGATION_SENSOR:
                mNavigationMode = SNVR_NAVIGATION_TOUCH;
                item.setIcon(R.drawable.ic_player_move);
                ToastUtils.showPlayerToast(getString(R.string.switch_manual_model));
                break;
            case SNVR_NAVIGATION_TOUCH:
                mNavigationMode = SNVR_NAVIGATION_SENSOR;
                item.setIcon(R.drawable.ic_player_normal);
                ToastUtils.showPlayerToast(getString(R.string.switch_auto_model));
                break;
        }

        mVideoView.setNavigationmode(mNavigationMode);
//        uiutils.setPreferenceKeyIntValue(this, Definition.KEY_SENSORMODE, mNavigationMode);

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (hasFocus) {
            toFullScreenMode();
        }
        super.onWindowFocusChanged(hasFocus);
    }

    public void toFullScreenMode() {

//		// The UI options currently enabled are represented by a bitfield.
//		// getSystemUiVisibility() gives us that bitfield.
//		int newUiOptions = 0;
//
//		// Navigation bar hiding:  Backwards compatible to ICS.
//		if (Build.VERSION.SDK_INT >= 14) {
//			newUiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
//			newUiOptions = newUiOptions | View.SYSTEM_UI_FLAG_LOW_PROFILE;
//		}
//
//		// Status bar hiding: Backwards compatible to Jellybean
//		if (Build.VERSION.SDK_INT >= 16) {
//			newUiOptions = newUiOptions | View.SYSTEM_UI_FLAG_FULLSCREEN;
//		}
//
//		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//			newUiOptions = newUiOptions | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
//		}
//
//		getWindow().getDecorView().setSystemUiVisibility(newUiOptions);
    }

    private void updateHistoryList(String videoPath, String videoName) {
        LogUtils.d("videoPath=" + videoPath);
        if (!TextUtils.isEmpty(videoPath)) {
            History history = new History(videoPath, videoName);
            history.save();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putBoolean(KEY_IS_ON_GLASS,isOFFGlass);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        isOFFGlass=savedInstanceState.getBoolean(KEY_IS_ON_GLASS);
        if(mVideoView!=null){
            initEysMode();
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.v(TAG, "onRestart");
        LogUtils.i("TEST","onRestart()");
    }


    private void initEysMode() {
        if(isOFFGlass){
            mToolbar.getMenu().findItem(R.id.glass_state).setIcon(R.drawable.ic_player_no_glasse);
            mVideoView.setEyesMode(Constant.GLASS_OFF);
        }else{
            mToolbar.getMenu().findItem(R.id.glass_state).setIcon(R.drawable.ic_player_glasses);
            mVideoView.setEyesMode(Constant.GLASS_ON);
        }
    }




}
